package com.qingxin.park.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.qingxin.park.entity.FarmPark;
import com.qingxin.park.vo.MapMarker;
import com.qingxin.sys.dao.Querier;
import com.qingxin.sys.dao.Updater;
import com.qingxin.sys.entity.LoginUser;
import com.qingxin.sys.mvc.PageParam;
import com.qingxin.sys.mvc.Pager;
import com.qingxin.sys.mvc.SysError;
import com.qingxin.sys.service.BaseService;
import com.qingxin.sys.support.SystemCfg;
import com.qingxin.sys.support.UploadFile;
import com.qingxin.sys.utils.BeanUtil;
import com.qingxin.sys.utils.StringUtils;
import com.qingxin.ui.bean.TreeNode;

/**
 * 园区
 * @author Administrator
 *
 */
@Service
public class FarmParkService extends BaseService<FarmPark, String> {
	
	@Autowired
	private SysUserParkRelService sysUserParkRelService;

	
	/**
	 * 获取菜单树数据
	 * @param groupid
	 * @param loginUser
	 * @param isParent
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<TreeNode> getUITreeData(String groupid, LoginUser loginUser, boolean isParent){
		List<TreeNode> list = new ArrayList<TreeNode>();
		if(loginUser == null){
			return list;
		}
		if(StringUtils.isEmpty(groupid) && !SystemCfg.isAdminUser(loginUser) && !SystemCfg.isSystemAdminUser(loginUser)){
			groupid = loginUser.getGroupid();
		}
		
		StringBuilder hql = new StringBuilder();
		hql.append("select new com.qingxin.park.entity.FarmPark(p.parkid, p.parkName)");
		hql.append(" from FarmPark p where p.isdel='0'");
		if(StringUtils.isNotEmpty(groupid) && !"0".equals(groupid)){
			hql.append(" and p.groupid='"+groupid.replace("'", "")+"' ");
		}
		if(!SystemCfg.isDataAdminUser(loginUser)){
			hql.append(" and p.parkid in (select distinct v.farmPark.parkid from SysUserParkRel v where v.sysUser.userid='"+loginUser.getUserid()+"')");
		}
		hql.append(" order by p.parkName asc");
		List<FarmPark> parks = listByHql(hql.toString());
		if(parks != null){
			for(FarmPark park : parks){
				list.add(new TreeNode(park.getParkid(), park.getParkName(), SystemCfg.UI_DATATYPE_PARK, null, isParent));
			}
		}
		return list;
	}
	
	
	@SuppressWarnings("unchecked")
	public List<TreeNode> getUITreeData(LoginUser loginUser, boolean isParent){
		List<TreeNode> list = new ArrayList<TreeNode>();
		if(loginUser == null){
			return list;
		}
		String groupid = null;
		if(!SystemCfg.isAdminUser(loginUser) && !SystemCfg.isSystemAdminUser(loginUser)){
			groupid = loginUser.getGroupid();
		}
		
		StringBuilder hql = new StringBuilder();
		hql.append("select new com.qingxin.park.entity.FarmPark(p.parkid, p.parkName)");
		hql.append(" from FarmPark p where p.isdel='0'");
		if(StringUtils.isNotEmpty(groupid) && !"0".equals(groupid)){
			hql.append(" and p.groupid like '"+groupid.replace("'", "")+"%' ");
		}
		if(!SystemCfg.isDataAdminUser(loginUser)){
			hql.append(" and p.parkid in (select distinct v.farmPark.parkid from SysUserParkRel v where v.sysUser.userid='"+loginUser.getUserid()+"')");
		}
		hql.append(" order by p.parkName asc");
		List<FarmPark> parks = listByHql(hql.toString());
		if(parks != null){
			for(FarmPark park : parks){
				list.add(new TreeNode(park.getParkid(), park.getParkName(), SystemCfg.UI_DATATYPE_PARK, null, isParent));
			}
		}
		return list;
	}
	
	
	@SuppressWarnings("unchecked")
	public List<TreeNode> getUITreeDataCompany(String companyid, String blockType, LoginUser loginUser, boolean isParent){
		List<TreeNode> list = new ArrayList<TreeNode>();
		if(loginUser == null){
			return list;
		}
		
		StringBuilder hql = new StringBuilder();
		hql.append("select new com.qingxin.park.entity.FarmPark(p.parkid, p.parkName)");
		hql.append(" from FarmPark p,ParkBlock b where p.isdel='0' and b.farmPark.parkid=p.parkid and b.isdel='0' ");
		
		hql.append(" and p.companyid='"+companyid+"' ");
		
		if(StringUtils.isNotEmpty(blockType)){
			hql.append(" and b.blockType='"+blockType.replace("'", "")+"' ");
		}
		
		if(!SystemCfg.isDataAdminUser(loginUser)){
			hql.append(" and p.parkid in (select distinct v.farmPark.parkid from SysUserParkRel v where v.sysUser.userid='"+loginUser.getUserid()+"')");
		}
		hql.append(" order by p.parkName asc");
		List<FarmPark> parks = listByHql(hql.toString());
		if(parks != null){
			Set<String> keySet = new HashSet<>();
			for(FarmPark park : parks){
				if(!keySet.contains(park.getParkid())){
					list.add(new TreeNode(park.getParkid(), park.getParkName(), SystemCfg.UI_DATATYPE_PARK, null, isParent));
					keySet.add(park.getParkid());
				}
			}
		}
		return list;
	}
	
	
	@SuppressWarnings("unchecked")
	public List<TreeNode> getUITreeDataCompanyAll(String companyid){
		List<TreeNode> list = new ArrayList<TreeNode>();
		StringBuilder hql = new StringBuilder();
		hql.append("select new com.qingxin.park.entity.FarmPark(p.parkid, p.parkName)");
		hql.append(" from FarmPark p where p.isdel='0' and p.companyid=? ");
		hql.append(" order by p.parkName asc");
		List<FarmPark> parks = listByHql(hql.toString(), companyid);
		if(parks != null){
			Set<String> keySet = new HashSet<>();
			for(FarmPark park : parks){
				if(!keySet.contains(park.getParkid())){
					list.add(new TreeNode(park.getParkid(), park.getParkName(), SystemCfg.UI_DATATYPE_PARK, null, true));
					keySet.add(park.getParkid());
				}
			}
		}
		return list;
	}
	
	
	/**
	 * 获取菜单树数据
	 * @param groupid
	 * @param loginUser
	 * @param isParent
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<TreeNode> getUITreeDataType(LoginUser loginUser, String blockType, boolean isParent){
		List<TreeNode> list = new ArrayList<TreeNode>();
		if(loginUser == null){
			return list;
		}
		String groupid = null;
		if(!SystemCfg.isAdminUser(loginUser) && !SystemCfg.isSystemAdminUser(loginUser)){
			groupid = loginUser.getGroupid();
		}
		
		StringBuilder hql = new StringBuilder();
		hql.append("select new com.qingxin.park.entity.FarmPark(p.parkid, p.parkName)");
		hql.append(" from FarmPark p,ParkBlock b where p.isdel='0' and b.farmPark.parkid=p.parkid and b.isdel='0' ");
		if(StringUtils.isNotEmpty(groupid) && !"0".equals(groupid)){
			hql.append(" and p.groupid like '"+groupid.replace("'", "")+"%' ");
		}
		if(StringUtils.isNotEmpty(blockType)){
			hql.append(" and b.blockType='"+blockType.replace("'", "")+"' ");
		}
		if(!SystemCfg.isDataAdminUser(loginUser)){
			hql.append(" and b.blockid in (select distinct v.parkBlock.blockid from SysUserBlockRel v where v.sysUser.userid='"+loginUser.getUserid()+"')");
		}
		
		hql.append(" order by p.parkName asc");
		List<FarmPark> parks = listByHql(hql.toString());
		if(parks != null){
			Set<String> keySet = new HashSet<>();
			for(FarmPark park : parks){
				if(!keySet.contains(park.getParkid())){
					list.add(new TreeNode(park.getParkid(), park.getParkName(), SystemCfg.UI_DATATYPE_PARK, null, isParent));
					keySet.add(park.getParkid());
				}
				
			}
		}
		return list;
	}
	
	
	/**
	 * 获取指定用户关联的园区数据
	 * @param loginUser
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<TreeNode> getParkData(LoginUser loginUser){
		List<TreeNode> list = new ArrayList<TreeNode>();
		if(loginUser == null){
			return list;
		}
		String groupid = null;
		if(StringUtils.isEmpty(groupid) && !SystemCfg.isAdminUser(loginUser) && !SystemCfg.isSystemAdminUser(loginUser)){
			groupid = loginUser.getGroupid();
		}
		
		StringBuilder hql = new StringBuilder();
		hql.append("select new com.qingxin.park.entity.FarmPark(p.parkid, p.parkName)");
		hql.append(" from FarmPark p where p.isdel='0'");
		
		if(StringUtils.isNotEmpty(groupid)){
			hql.append(" and p.groupid like '"+groupid+"%' ");
		}
		
		if(!SystemCfg.isDataAdminUser(loginUser)){
			hql.append(" and p.parkid in (select distinct v.farmPark.parkid from SysUserParkRel v where v.sysUser.userid='"+loginUser.getUserid()+"')");
		}
		hql.append(" order by p.parkName asc");
		List<FarmPark> parks = listByHql(hql.toString());
		if(parks != null){
			for(FarmPark park : parks){
				list.add(new TreeNode(park.getParkid(), park.getParkName(), false));
			}
		}
		return list;
	}
	
	/**
	 * 获取园区编码最大值
	 * @param pageParam
	 * @param loginUser
	 * @return
	 */
	public String getParkNoMax(String companyid){
		String parkNo = (String) getByHql("select max(parkNo) from FarmPark where companyid=?", companyid);
		return parkNo;
	}
	
	
	@SuppressWarnings("unchecked")
	public List<FarmPark> listParks(String companyid){
		String hql = "select new com.qingxin.park.entity.FarmPark(" +
				"parkid, parkNo, parkName, logoUrl, remark, parkLevel, createTime)" +
				" from FarmPark where isdel='0' and companyid=? order by createTime desc";
		List<FarmPark> list = listByHql(hql, companyid);
		return list;
	}
	
	
	/**
	 * 获取特色园区，首页展示
	 * @param nums
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<FarmPark> listTeseParks(int nums){
		Querier querier = Querier.create("select new com.qingxin.park.entity.FarmPark(" +
				"parkid, parkNo, parkName, logoUrl, remark, parkLevel, createTime)" +
				" from FarmPark where isdel='0' and teseStatus='1' order by createTime desc");
		querier.setMaxResults(nums);
		List<FarmPark> list = listByQuerier(querier);
		return list;
	}
	
	
	public Pager listPageTeseParks(PageParam pageParam){
		Querier querier = Querier.create("select new com.qingxin.park.entity.FarmPark(" +
				"parkid, parkNo, parkName, logoUrl, remark, parkLevel, createTime)" +
				" from FarmPark where isdel='0' and teseStatus='1' order by createTime desc");
		Pager pager = pageByQuerier(querier, pageParam);
		return pager;
	}
	
	
	/**
	 * 获取园区列表分页数据
	 * @param parkName
	 * @param parkStatus
	 * @param pageParam
	 * @param loginUser
	 * @return
	 */
	public Pager list(String groupid, String parkName, String parkStatus, PageParam pageParam, LoginUser loginUser){
		if(StringUtils.isEmpty(groupid) && !SystemCfg.isAdminUser(loginUser) && !SystemCfg.isSystemAdminUser(loginUser)){
			groupid = loginUser.getGroupid();
		}
		
		Querier querier = Querier.create("select new com.qingxin.park.entity.FarmPark(" +
				"p.parkid, p.parkNo, p.parkName, p.contactPerson, p.mobile, p.parkLevel, p.parkStatus, p.teseStatus)" +
				" from FarmPark p where p.isdel='0' ");
		if(StringUtils.isNotEmpty(groupid)){
			groupid = groupid.replace("'", "");
			querier.append(" and p.groupid like :groupid ");
			querier.setParam("groupid", groupid+"%");
		}
		if(!SystemCfg.isDataAdminUser(loginUser)){
			querier.append(" and p.parkid in (select distinct v.farmPark.parkid from SysUserParkRel v where v.sysUser.userid=:userid)");
			querier.setParam("userid", loginUser.getUserid());
		}
		if(StringUtils.isNotEmpty(parkName)){
			parkName = parkName.replace("'", "");
			querier.append(" and (p.parkName like :parkName or p.parkNo like :parkNo) ");
			querier.setParam("parkName", "%"+parkName+"%");
			querier.setParam("parkNo", "%"+parkName+"%");
		}
		
		querier.append(pageParam.getOrderby(" order by p.parkNo desc"));
		
		Pager pager = pageByQuerier(querier, pageParam);
		return pager;
	}
	
	
	/**
	 * 导出园区信息
	 * @param groupid
	 * @param loginUser
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<FarmPark> listFarmParks(String groupid, LoginUser loginUser){
		if(StringUtils.isEmpty(groupid) && !SystemCfg.isAdminUser(loginUser) && !SystemCfg.isSystemAdminUser(loginUser)){
			groupid = loginUser.getGroupid();
		}
		
		Querier querier = Querier.create("select new com.qingxin.park.entity.FarmPark(" +
				"p.parkid, p.parkNo, p.parkName, p.contactPerson, p.mobile, p.parkLevel, p.parkStatus, p.teseStatus)" +
				" from FarmPark p where p.isdel='0' ");
		if(StringUtils.isNotEmpty(groupid)){
			groupid = groupid.replace("'", "");
			querier.append(" and p.groupid like :groupid ");
			querier.setParam("groupid", groupid+"%");
		}
		if(!SystemCfg.isDataAdminUser(loginUser)){
			querier.append(" and p.parkid in (select distinct v.farmPark.parkid from SysUserParkRel v where v.sysUser.userid=:userid)");
			querier.setParam("userid", loginUser.getUserid());
		}
		
		querier.append(" order by p.parkNo desc");
		
		return listByQuerier(querier);
	}
	
	
	/**
	 * 按分页获取所有园区数据
	 * @param pageParam
	 * @return
	 */
	public Pager listAllPager(PageParam pageParam){
		Querier querier = Querier.create("from FarmPark p where p.isdel='0' order by p.parkName asc");
		Pager pager = pageByQuerier(querier, pageParam);
		return pager;
	}
	
	
	@SuppressWarnings("unchecked")
	public List<FarmPark> listForApp(String search, PageParam pageParam, LoginUser loginUser){
		Querier querier = Querier.create("from FarmPark p where p.isdel='0' ");
		
		String groupid = loginUser.getGroupid();
		if(StringUtils.isNotEmpty(groupid)){
			groupid = groupid.replace("'", "");
			querier.append(" and p.groupid like :groupid ");
			querier.setParam("groupid", groupid+"%");
		}
		if(!SystemCfg.isDataAdminUser(loginUser)){
			querier.append(" and p.parkid in (select distinct v.farmPark.parkid from SysUserParkRel v where v.sysUser.userid=:userid)");
			querier.setParam("userid", loginUser.getUserid());
		}
		
		if(StringUtils.isNotEmpty(search)){
			search = search.replace("'", "");
			
			System.out.println("search="+search);
			
			querier.append(" and (p.parkName like :parkName) ");
			querier.setParam("parkName", "%"+search+"%");
		}
		querier.append(pageParam.getOrderby(" order by p.createTime desc"));
		List<FarmPark> list = listByQuerier(querier, pageParam);
		return list;
	}
	
	
	
	/**
	 * 添加园区
	 * @param park
	 * @param loginUser
	 * @param request
	 * @return
	 */
	public SysError add(FarmPark park, LoginUser loginUser, HttpServletRequest request){
		if(isNameDuplicate(park.getParkName(), null)){
			return new SysError("该名称已存在");
		}
//		if(isNoDuplicate(park.getParkNo(), null)){
//			return new SysError("该编号已存在");
//		}
		
		//park.setLogoUrl("");
		park.setRegionid("");
		park.setDescrib("");
		if(park.getParkLevel() == null){
			park.setParkLevel(1);
		}
		if(park.getParkStatus() == null){
			park.setParkStatus("1");
		}
		park.setIsdel("0");
		park.setTeseStatus("0");
		Date now = new Date();
		park.setCreateTime(now);
		park.setUpdateTime(now);
		park.setCreateBy(loginUser.getLogin_name());
		park.setUpdateBy(loginUser.getLogin_name());
		
		if(StringUtils.isNotEmpty(park.getLogoUrl())){
			UploadFile.moveTmpTo(park.getLogoUrl(), UploadFile.DIR_FARM_IMG);
		}
		
		this.save(park);
		
		//添加用户园区关联关系
		if(!SystemCfg.isDataAdminUser(loginUser)){
			sysUserParkRelService.addUserParkRel(loginUser.getUserid(), park.getParkid(), loginUser);
		}
		
		return null;
	}
	
	
	/**
	 * 修改园区信息
	 * @param park
	 * @param loginUser
	 * @param request
	 * @return
	 */
	public SysError update(FarmPark park, LoginUser loginUser, HttpServletRequest request){
		FarmPark old = getSafeEntity(park.getParkid());
		if(old==null){
			return new SysError("参数错误");
		}
		if(isNameDuplicate(park.getParkName(), park.getParkid())){
			return new SysError("该名称已存在");
		}
		if(isNoDuplicate(park.getParkNo(), park.getParkid())){
			return new SysError("该编号已存在");
		}
		
		if(StringUtils.isNotEmpty(park.getLogoUrl()) && !park.getLogoUrl().equals(old.getLogoUrl())){
			UploadFile.moveTmpTo(park.getLogoUrl(), UploadFile.DIR_FARM_IMG);
		}
		
		String fields = "parkName,parkAddress,contactPerson,phone,mobile,email,remark,parkLevel,parkStatus,teseStatus,logoUrl,wechat,lat,lng";
		BeanUtil.setTargetFields(old, park, fields, true);
		
		old.setUpdateBy(loginUser.getLogin_name());
		old.setUpdateTime(new Date());
		
		Updater<FarmPark> updater = new Updater<>(old, fields+",updateBy,updateTime");
		this.update(updater);
		
		return null;
	}
	
	
	
	/**
	 * 修改园区介绍
	 * @param parkid
	 * @param describ
	 * @param loginUser
	 * @return
	 */
	public SysError updateDescrib(String parkid, String describ, LoginUser loginUser){
		FarmPark old = getSafeEntity(parkid);
		if(old==null){
			return new SysError("参数错误");
		}
		old.setDescrib(describ);
		old.setUpdateBy(loginUser.getLogin_name());
		old.setUpdateTime(new Date());
		
		Updater<FarmPark> updater = new Updater<>(old, "describ,updateBy,updateTime");
		this.update(updater);
		
		return null;
	}
	
	/**
	 * 修改园区特色属性
	 * @param parkid
	 * @param teseStatus
	 * @param loginUser
	 * @return
	 */
	public Object updateTese(String[] parkids,String teseStatus,  LoginUser loginUser, HttpServletRequest request){
		for(String parkid : parkids){
			FarmPark old = getSafeEntity(parkid);
			if(old==null){
				return new SysError("参数错误");
			}
			old.setTeseStatus(teseStatus);
			old.setUpdateBy(loginUser.getLogin_name());
			old.setUpdateTime(new Date());
			
			Updater<FarmPark> updater = new Updater<>(old, "teseStatus,updateBy,updateTime");
			this.update(updater);
		}
		return null;
	}
	
	/**
	 * 删除园区信息
	 * @param parkids
	 * @param loginUser
	 * @param request
	 * @return
	 */
	public Object delete(String[] parkids, LoginUser loginUser, HttpServletRequest request){
		for(String parkid : parkids){
			FarmPark park = get(parkid);
			if(park==null){
				continue;
			}
			Object obj = getByHql("select blockid from ParkBlock where farmPark.parkid=?", parkid);
			if(obj!=null){
				return new SysError("园区 “"+park.getParkName()+"” 下有地块信息，不能删除.");
			}
			
			this.delete(park);
		}
		return null;
	}
	
	
	
	/**
	 * 判断指定名称是否被使用
	 * @param parkName
	 * @param parkid
	 * @return
	 */
	public boolean isNameDuplicate(String parkName, String parkid){
		return isExists("parkName", parkName, "parkid", parkid);
	}
	
	/**
	 * 判断指定编号是否被使用
	 * @param parkNo
	 * @param parkid
	 * @return
	 */
	public boolean isNoDuplicate(String parkNo, String parkid){
		return isExists("parkNo", parkNo, "parkid", parkid);
	}
	
	
	/**
	 * 获取园区在地图上的坐标信息
	 * @param wlng 左边界经度
	 * @param elng 右边界经度
	 * @param nlat 上边界纬度
	 * @param slat 下边界纬度
	 * @param zoom 地图缩放级别
	 * @param loginUser
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<MapMarker> listMapMarker(BigDecimal wlng, BigDecimal elng,
			BigDecimal nlat, BigDecimal slat, int zoom, LoginUser loginUser){
		Querier querier = Querier.create("select new com.qingxin.park.vo.MapMarker(" +
				"p.parkid, 'park', p.parkName, p.parkAddress, p.lat, p.lng)" +
				" from FarmPark p where p.isdel='0' ");
		//左边界经度
		querier.append(" and p.lng>=:wlng ");
		querier.setParam("wlng", wlng);
		//右边界经度
		querier.append(" and p.lng<=:elng ");
		querier.setParam("elng", elng);
		//上边界纬度
		querier.append(" and p.lat<=:nlat ");
		querier.setParam("nlat", nlat);
		//下边界纬度
		querier.append(" and p.lat>=:slat ");
		querier.setParam("slat", slat);
		
		querier.append(" order by p.createTime asc");
		
		List<MapMarker> list = listByQuerier(querier);
		if(list == null){
			return new ArrayList<>();
		}
		return list;
	}
	
	
	
}
